package com.jd.ty.web.interceptor;

import java.util.Map;

import com.jd.ty.pojo.Permission;
import com.jd.ty.pojo.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class AclInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {

		ActionContext actionContext = invocation.getInvocationContext();

		Map session = actionContext.getSession();
		if (session != null && session.get(LoginInterceptor.USER_SESSION_KEY) != null) {
			User user = (User) session.get(LoginInterceptor.USER_SESSION_KEY);
			if(user.getRole().isAdmin()){
				return invocation.invoke();
			}
			for (Permission p : user.getRole().getPermissions()) {
				String sapces = p.getFunction().getNameSpace();
				if (sapces != null) {
					String[] spaceArray = sapces.split(",");
					for (String sapce : spaceArray) {
						if (sapce.equals(invocation.getProxy().getNamespace()))
							return invocation.invoke();
					}
				}

			}

		}
		throw new Exception("没有权限");

	}
}
